package yue.shen.android.demo.select

import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.BitmapImageViewTarget
import yue.shen.android.demo.R
import yue.shen.android.demo.databinding.ActivityCameraPreviewBinding

class CameraPreviewActivity : AppCompatActivity() {

    companion object {

        private const val IMAGE_PATH = "image_path"

        fun startActivity(activity: Activity, path: String, requestCode: Int) {
            val intent = Intent(activity, CameraPreviewActivity::class.java)
            intent.putExtra(IMAGE_PATH, path)
            activity.startActivityForResult(intent, requestCode)
        }
    }

    private var imagePath = ""

    private lateinit var viewBinding: ActivityCameraPreviewBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewBinding = ActivityCameraPreviewBinding.inflate(layoutInflater)
        setContentView(viewBinding.root)
        initView()
    }

    private fun initView() {
        imagePath = intent.getStringExtra(IMAGE_PATH) ?: ""
        viewBinding.ivBack.setOnClickListener { finish() }
        viewBinding.tvAgain.setOnClickListener {
            setResult(-2)
            finish()
        }
        viewBinding.tvUsePic.setOnClickListener {
            val intent = Intent()
            intent.putExtra("data",imagePath)
            setResult(Activity.RESULT_OK,intent)
            finish()
        }

        val options: RequestOptions = RequestOptions()
            .placeholder(R.drawable.ic_placeholder)
            .centerCrop()
            .diskCacheStrategy(DiskCacheStrategy.ALL)
        Glide.with(this)
            .asBitmap()
            .load(imagePath)
            .apply(options)
            .into(object : BitmapImageViewTarget(viewBinding.imageView) {
                override fun setResource(resource: Bitmap?) {
                    val circularBitmapDrawable =
                        RoundedBitmapDrawableFactory.create(resources, resource)
                    viewBinding.imageView.setImageDrawable(circularBitmapDrawable)
                }
            })
    }

}